import React, { useEffect } from "react";
import "@/tailwind-variables.less";

const imgs = [
  "./imgs/lazyLoad/1.webp",
  "./imgs/lazyLoad/2.webp",
  "./imgs/lazyLoad/3.webp",
  "./imgs/lazyLoad/4.webp",
  "./imgs/lazyLoad/5.webp",
  "./imgs/lazyLoad/6.webp",
  "./imgs/lazyLoad/7.webp",
  "./imgs/lazyLoad/8.webp",
  "./imgs/lazyLoad/9.webp",
  "./imgs/lazyLoad/10.webp",
  "./imgs/lazyLoad/11.webp",
  "./imgs/lazyLoad/12.webp",
];

function lazyLoad(ele: HTMLElement) {
  const images: NodeListOf<HTMLElement> = document.querySelectorAll(".lazy");
  const scrollTop = ele.scrollTop;
  images.forEach((img) => {
    if (img.getBoundingClientRect().top < ele.clientHeight + scrollTop) {
      img.setAttribute("src", img.getAttribute("data-src")!);
      img.classList.remove("lazy");
    }
  });
}

export const ImageLazyLoadCustom: React.FC = () => {
  useEffect(() => {
    let lazyLoadThrottleTimeout: any;
    const ele: HTMLElement | null = document.querySelector("#scrollBox");
    if (ele) {
      lazyLoad(ele);
      ele.addEventListener("scroll", () => {
        if (lazyLoadThrottleTimeout) {
          clearTimeout(lazyLoadThrottleTimeout);
        }
        lazyLoadThrottleTimeout = setTimeout(() => lazyLoad(ele), 20);
      });
    }
  }, []);
  return (
    <div className="flex justify-center flex-col items-center ">
      <h1 className="text-2xl font-bold">图片懒加载</h1>
      <div id="scrollBox" className="h-[600px] overflow-auto">
        <div className="mt-2 w-[1024px] flex gap-2 flex-col">
          {imgs.map((img, index) => (
            <img className="lazy h-[200px]" key={index} data-src={img} alt="" />
          ))}
        </div>
      </div>
    </div>
  );
};
